<script setup lang="ts">
import { shouhuositelist } from '@/common/api/hbMarket';
import { ref, computed, watch } from 'vue';
import type { AddressListAddress } from 'vant';
import { useOrderInfo } from '@/stores/orderInfo';
import { showToast } from 'vant';
import { copyHandler } from '@/utils/util';

const orderInfo = useOrderInfo();
const orderDetail = computed(() => orderInfo.state.info);

withDefaults(
  defineProps<{
    oid?: string;
  }>(),
  {
    oid: '',
  }
);

interface UserAddressItem {
  province: string; // 省
  city: string; // 市
  area: string; // 区
  id: number; // 收货地址 id
  ifdefault: 0 | 1; // 是否为默认地址 1：默认
  mobile: string; // 收货人手机号
  name: string; // 收货人姓名
  site: string; // 详细地址
}

const showPopup = ref(false);

// 收货地址列表
const list = ref<UserAddressItem[]>([]);
const addressList = computed<AddressListAddress[]>(() => {
  if (!list.value.length) return [];
  return list.value.map((v: any) => {
    return {
      id: v.id,
      name: v.name,
      tel: v.mobile,
      mobile: v.mobile,
      address: v.province + v.city + v.area + v.site,
      isDefault: v.ifdefault === 1,
    };
  });
});
// 选中收货地址
const chosenAddressId = ref<number | undefined>();
const chosenAddressItem = computed<UserAddressItem | undefined>(() =>
  list.value.find((v) => v.id === chosenAddressId.value)
);
watch(chosenAddressItem, () => {
  orderInfo.setOrderInfo({
    shouhuoid: String(chosenAddressItem.value?.id || ''),
    shuoming: chosenAddressItem.value?.name || '',
  });
});

const onLoad = async () => {
  try {
    const res = await shouhuositelist({});
    list.value = res.result || [];
    if (list.value.length) {
      chosenAddressId.value = list.value.find((v) => v.ifdefault === 1)?.id;
    }
  } catch {
    /** empty */
  }
};
onLoad();

const handleClick = () => {
  if (!list.value.length) {
    return showToast('请前往APP端添加收货地址');
  }
  showPopup.value = true;
};

// 文本复制
const copyText = (text: string) => {
  const { errMsg } = copyHandler({ data: text });
  if (errMsg.indexOf('ok') > -1) {
    showToast('复制成功');
  }
  console.log(errMsg);
};
</script>
<template>
  <div class="userAddress">
    <van-cell-group inset>
      <van-cell v-if="oid" :title="`${orderDetail.shuoming} ${orderDetail.shouhuo_mobile}`" center>
        <template #label>
          <div class="flex justify-between items-center">
            <div class="flex-1 mr-2">
              {{ orderDetail.shouhuo_site }}
            </div>
            <van-button size="mini" @click="copyText(orderDetail.shouhuo_site || '')">复制</van-button>
          </div>
        </template>
      </van-cell>
      <van-cell
        v-else
        @click="handleClick"
        :title="chosenAddressItem ? `${chosenAddressItem.name}  ${chosenAddressItem.mobile}` : '-'"
        is-link
        center
        :label="
          chosenAddressItem
            ? `${chosenAddressItem.province}${chosenAddressItem.city}${chosenAddressItem.area}${chosenAddressItem.site}`
            : '请选择收货地址'
        "
      />
    </van-cell-group>
    <!-- 底部弹出 -->
    <van-popup v-model:show="showPopup" position="bottom" round safe-area-inset-bottom>
      <van-address-list
        v-model="chosenAddressId"
        :list="addressList"
        @click-item="showPopup = false"
        :show-add-button="false"
        right-icon=""
        default-tag-text="默认"
      />
    </van-popup>
  </div>
</template>
<style lang="less" scoped>
.userAddress {
}
</style>
